package com.hoozhi.common.web.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


/**
 * 上下文信息拦截器
 * 包括登录信息、权限信息
 * 
 * @author pharen
 * 
 */
public class AdminContextInterceptor extends HandlerInterceptorAdapter {
	
	private String[] excludeUrls;

	private String loginUrl;
	private String processUrl;
	private String returnUrl;
	
	public String[] getExcludeUrls() {
		return excludeUrls;
	}

	public void setExcludeUrls(String[] excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	public String getProcessUrl() {
		return processUrl;
	}

	public void setProcessUrl(String processUrl) {
		this.processUrl = processUrl;
	}

	public String getReturnUrl() {
		return returnUrl;
	}

	public void setReturnUrl(String returnUrl) {
		this.returnUrl = returnUrl;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		
		HttpSession s = request.getSession();

		Object user = s.getAttribute("user");    //取session值

		String servletPath = request.getServletPath();

		servletPath = servletPath == null ? "" : servletPath;

		int index = servletPath.lastIndexOf("/");

		if (!"/".equals(servletPath) && index == servletPath.length() - 1) {
			servletPath = servletPath.substring(0, servletPath.length() - 1);
		}

		if ("/".equals(servletPath) || servletPath.indexOf("/css/") != -1
				|| servletPath.indexOf("/js/") != -1
				|| servletPath.indexOf("/images/") != -1
				|| servletPath.indexOf("/fckeditor/") != -1
				|| servletPath.indexOf("/verifyCode") != -1  //登录验证码
				|| servletPath.indexOf("/login") != -1       //登录controller
				|| servletPath.indexOf("/toLogin") != -1     //拦截后跳到登录页
				|| (servletPath.indexOf("/toIndex") != -1 && user != null)) {  //登录验证成功后执行的controller

			return true;
		}else if(user != null){
			return true;
		} else {
			request.setAttribute("servletPath", servletPath);
			try {
				response.sendRedirect(basePath + loginUrl);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return false;
			//throw new HttpSessionRequiredException("您未登录或已登录超时！");
		}
	}
	
}